package cn.elead.chaos.mybatils.exception;

import java.sql.SQLFeatureNotSupportedException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.dao.DeadlockLoserDataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.dao.RecoverableDataAccessException;

import cn.elead.chaos.api.enums.ExStatus;
import cn.elead.chaos.api.web.IExceptionResolverService;
import cn.elead.chaos.framework.util.ResponseUtils;
import cn.elead.chaos.framework.web.global.ErrorCodeEnum;
import lombok.extern.slf4j.Slf4j;

/**
 * 自定义异常处理
 * <p>
 * https://blog.csdn.net/weixin_39520967/article/details/99706639<br>
 * https://www.jianshu.com/p/cf1278d687e4<br>
 * https://blog.csdn.net/wj123446/article/details/77873661<br>
 * https://blog.csdn.net/qq_34178998/article/details/89326254<br>
 * 
 */
@Slf4j
public class SqlExceptionResolverService implements IExceptionResolverService {

	@Override
	public ExStatus doException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex, Object view) {
		if (ex instanceof DeadlockLoserDataAccessException) {
			log.error(ex.getMessage(), ex);
			ResponseUtils.sendFail(request, response, ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("当前的操作因为死锁而失败"), ex);
			return ExStatus.HIT;
		}
		if (ex instanceof DataIntegrityViolationException) {
			log.error(ex.getMessage(), ex);
			ResponseUtils.sendFail(request, response, ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("Insert或Update数据时违反了完整性，例如违反了惟一性限制"), ex);
			return ExStatus.HIT;
		}
		if (ex instanceof RecoverableDataAccessException) {
			log.error(ex.getMessage(), ex);
			ResponseUtils.sendFail(request, response, ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("获取到数据库无效的连接"), ex);
			return ExStatus.HIT;
		}
		if (ex instanceof SQLFeatureNotSupportedException) {
			log.error(ex.getMessage(), ex);
			ResponseUtils.sendFail(request, response, ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("数据库操作异常"), ex);
			return ExStatus.HIT;
		}
		if (ex instanceof InvalidDataAccessApiUsageException) {
			log.error(ex.getMessage(), ex);
			ResponseUtils.sendFail(request, response, ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("数据库操作异常"), ex);
			return ExStatus.HIT;
		}
		return ExStatus.SKIP;
	}

}
